package task;

import UserAndGroup.Creat;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>类描述：角色和任务的绑定查询。</p>
 *
 * @author 贾亮
 * @version v1.0.0.1。
 * @since JDK1.8。
 * <p>创建日期：2018/3/9 10:48。</p>
 */
public class Main {
    public static void main(String[] args) {
        // 获取流程引擎实例
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 获取身份服务组件
        IdentityService identityService = processEngine.getIdentityService();
        // 新建用户
        User user = Creat.creatUser(identityService, "user1", "张三", "last", "123@163.com", "123");
        // 新建用户组
        Group group1 = Creat.createGroup(identityService, "group1", "经理组", "manager");
        Group group2 = Creat.createGroup(identityService, "group2", "员工组", "employee");
        // 获取任务服务组件
        TaskService taskService = processEngine.getTaskService();
        // 创建第一个任务
        Task task1 = taskService.newTask("task1");
        task1.setName("申请假期");
        taskService.saveTask(task1);
        // 创建第一个任务
        Task task2 = taskService.newTask("task2");
        task2.setName("批准假期");
        taskService.saveTask(task2);
        // 任务绑定权限
        taskService.addCandidateGroup("task1", group2.getId());
        taskService.addCandidateUser("task1", user.getId());
        taskService.addCandidateGroup("task2", group1.getId());
        // 根据用户组查询任务
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup(group1.getId()).list();
        System.out.println("经理组的候选任务有：");
        for (Task task : tasks) {
            System.out.println(task.getName());
        }
        // 根据用户查询任务
        tasks = taskService.createTaskQuery().taskCandidateUser(user.getId()).list();
        System.out.println("张三的候选任务有：");
        for (Task task : tasks) {
            System.out.println(task.getName());
        }
        // 查询多个用户组的候选任务
        List<String> groups = new ArrayList<>();
        groups.add(group1.getId());
        groups.add(group2.getId());
        tasks = taskService.createTaskQuery().taskCandidateGroupIn(groups).list();
        System.out.println("经理组和员工组的候选任务有：");
        for (Task task : tasks) {
            System.out.println(task.getName());
        }
        // 查询权限数据
        List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task1.getId());
        System.out.println("申请假期的关系数据量：" + identityLinks.size());
        // 关闭流程引擎，删除数据库表
        processEngine.close();
    }
}
